/*
 * ssp.c
 *
 *  Created on: 12/12/2009
 *      Author: Kimi
 */
#include "cpu/spi.h"


void spi_LCDSoftwareInit() {
	// set io direction
	LCD_DIR |= (LCD_MOSI | LCD_SCK | LCD_CS | LCD_RESET); //Assign LCD pins as Outputs

	// pin functionality as IO
	SPI_PINSEL &= ~( (3<<SPI_SCK_FUNCBIT) | (3<<SPI_MISO_FUNCBIT) |
			(3<<SPI_MOSI_FUNCBIT) | (3<<SPI_SS_FUNCBIT) );
}

void spi_LCDHardwareInit(unsigned int speed) {
	// PCLK = 60MHz
	LCD_DIR |= (LCD_MOSI | LCD_SCK | LCD_CS | LCD_RESET);

	// reset Pin-Functions
	SPI_PINSEL &= ~( (3<<SPI_SCK_FUNCBIT) | (3<<SPI_MISO_FUNCBIT) |
			(3<<SPI_MOSI_FUNCBIT) | (3<<SPI_SS_FUNCBIT) );

	// set Pin Functions
	SPI_PINSEL |= ((1<<SPI_SCK_FUNCBIT) | (0<<SPI_MISO_FUNCBIT) |
			(1<<SPI_MOSI_FUNCBIT) | (0<<SPI_SS_FUNCBIT));

	//SSPCR1 = 0; //disable
	S0SPCR = 0;

	//speed
	S0SPCCR = 0x08;

	// CPOL = 0 CPHA = 0 9bits SPI
	//SSPCR0 = ((SPI_DATABITS-1)<<0) | (0<<SPI_CPOL) | (16<<SPI_SCR);
	S0SPCR = 0x924;

	//SSPCR1 |= (1<<SSP_SSE);

	//SSPCPSR = 2;

	LCD_SET = LCD_CS;
	LCD_CLR = LCD_RESET;
}

void spi_DeInit() {
	// everything as Input IO
	// reset Pin-Functions
	SPI_PINSEL &= ~( (3<<SPI_SCK_FUNCBIT) | (3<<SPI_MISO_FUNCBIT) |
			(3<<SPI_MOSI_FUNCBIT) | (3<<SPI_SS_FUNCBIT) );

	// set io direction
	LCD_DIR &= ~(LCD_MOSI | LCD_SCK | LCD_CS | LCD_RESET); //Assign LCD pins as input
}

void spi_LCDSend(unsigned char cmd, unsigned char data) {
	LCD_CLR = LCD_CS; // enable chip, p0.20 goes low
#ifdef USE_SOFT_SPI_FOR_LCD
	char j;
	if (cmd == 1) {
		LCD_CLR = LCD_MOSI; // output low on data out (9th bit low = command), p0.19
	}
	else {
		LCD_SET = LCD_MOSI;
	}

	LCD_CLR = LCD_SCK; // send clock pulse
	LCD_SET = LCD_SCK;

	for (j = 0; j < 8; j++) {
		if ((data & 0x80) == 0x80)
			LCD_SET = LCD_MOSI;
		else
			LCD_CLR = LCD_MOSI;

		LCD_CLR = LCD_SCK; // send clock pulse
		LCD_SET = LCD_SCK;

		data <<= 1;
	}
#else
	if (cmd == 1) {
		//SSPDR = data & ~0x0100;
		S0SPDR = data & ~0x0100;
	}
	else {
		//SSPDR = data | 0x0100;
		S0SPDR = data | 0x0100;
	}
	//while (SSPSR & 0x10);
	while (!(S0SPSR & 0x80));
#endif
	LCD_SET = LCD_CS; // disable
}
